#include "app_pool.h"
#include "log/log.h"
#include <mqueue.h>
#include <pthread.h>
#include <stdlib.h>

static char *mq_name = "/app_pool_mq";
static mqd_t mq_fd; // file desctription
static int thread_count;
static pthread_t *thread_pool;

static void *pool_thread_fun(void *argv) {
    // 不断地从消息队列中获取任务并执行
    Task task;
    while (1) {
        ssize_t len = mq_receive(mq_fd, (char *)&task, sizeof(Task), NULL);
        if (len == sizeof(Task)) {
            task.task_fun(task.argv);
        }
    }
}

int app_pool_init(int size)
{
    // 1. 创建消息队列
    struct mq_attr attr;
    attr.mq_maxmsg = 5;
    attr.mq_msgsize = sizeof(Task);
    mq_fd = mq_open(mq_name, O_CREAT | O_RDWR, 0644, &attr);
    if (mq_fd == -1) {
        log_error("创建或打开消息队列失败");
        return -1;
    }

    // 2. 创建线程池
    thread_count = size;
    thread_pool = (pthread_t *)malloc(sizeof(pthread_t) * size);
    for (int i = 0; i < size; i++) {
        pthread_create(thread_pool+i, NULL, pool_thread_fun, NULL);
    }

    return 0;
}

void app_pool_close(void)
{
    // 1. 停止所有线程
    for (int i = 0; i < thread_count; i++)
    {
        pthread_cancel(thread_pool[i]);
        pthread_join(thread_pool[i], NULL);
    }
    free(thread_pool);

    // 2. 关闭并删除消息队列
    mq_close(mq_fd);
    mq_unlink(mq_name);
}

void app_pool_registerTask(int (*task_fun)(void *argv), void *argv)
{
    // 1. 创建任务
    Task task = {
        .task_fun = task_fun,
        .argv = argv
    };
    // 2. 将任务发送到消息队列
    mq_send(mq_fd, (char *)&task, sizeof(Task), 1);
}
